package com.typhoon.spring_shiro.controller.resolver;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

/**
 * web层统一异常处理类
 * 
 * @author Typhoon
 * @date 2017-05-22 18:17
 * @since V2.0
 */
public class WebExceptionResolver implements HandlerExceptionResolver {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(WebExceptionResolver.class);		

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		LOGGER.info("捕获web层异常",ex);
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("code", "999");
        results.put("msg", "系统异常");
        if(ex instanceof UnauthenticatedException || ex instanceof UnauthorizedException) {//授权异常
            results.put("code", "403");
            results.put("msg", "无权操作");
        }
		ModelAndView mv = new ModelAndView();  
        /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */  
        FastJsonJsonView view = new FastJsonJsonView();  
        view.setAttributesMap(results);
        mv.setView(view);   
        return mv;  
	}

}
